﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using Chire.wechat.Menu;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Specialized;
using Chire.ChireInter.Wechat.Model;

namespace Chire.wechat
{
    public class sucaiModel {
        public string type { get; set; }
        public string offset { get; set; }
        public string count { get; set; }

    }

    public class Wechat_AccessToken
    {

        #region 获取AccessToken
        public string getAccessToken()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constance.wechatAppID + "&secret=" + Constance.wechatAccessSecret;
            string info = HttpGet(url, "");

            JObject jo = (JObject)JsonConvert.DeserializeObject(info);
            string access_token = jo["access_token"].ToString();

            return access_token;
        }
        #endregion

        #region 微信授权-获取微信code
        /// <summary>
        /// 获取微信Code
        /// </summary>

        /// <param name="redirectUrl">返回的登录地址，要进行Server.Un编码</param>
        /// <param name="isWap">true=微信内部登录 false=pc网页登录</param>
        public string GetWeiXinCode(string redirectUrl, bool isWap)
        {
            string appId = Constance.wechatAppID;
            var r = new Random();
            //微信登录授权
            //string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
            //微信OpenId授权
            //string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
            //微信用户信息授权
            var url = "";
            if (isWap)
            {
                url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" +
                      redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            }
            else
            {
                url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl +
                      "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
            }
            return url;
        }
        #endregion
                
        #region 微信授权-根据code获取AccessToken
        public string getAccessTokenWithCode(string code) {
            string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constance.wechatAppID + "&secret=" + Constance.wechatAccessSecret + "&code="
             + code + "&grant_type=authorization_code";

            return HttpGet(url,"");
      
        }
        #endregion

        #region 微信授权- 获取用户信息
        public string getUserInfoWithTokenOpenId(string token,string openId) { 
            string nUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openId+"&lang=zh_CN";

            return HttpGet(nUrl, "");
        }
        #endregion

        #region 微信模板消息
        #region 微信进行签到
        public string sendMsgWithSignIn(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatSignIn,"");

            return callback;
        }
        #endregion

        #region 微信进行签退
        public string sendMsgWithSignOut(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatSignOut,"");
            return callback;
        }
        #endregion

        #region 微信成员加入信息
        public string memberTeacherAddInfo(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatMemberJoin,"");
            return callback;
        }
        #endregion

        #region 微信进行开课提醒
        public string wechatStartClassMsg(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatClassWillStart,"");
            return callback;
        }
        #endregion

        #region 微信进行下课提醒
        public string wechatWillEndClassMsg(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatClassWillEnd,"");
            return callback;
        }
        #endregion

        #region 微信进行下课了10分钟后未签退提示
        public string wechatClassEndWaringSignOut(string openId, WechatModelDataList list) {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatClassEndNotSignOut,"");
            return callback;
        }
        #endregion

        #region 微信进行上课了10分钟后还是没有签到的
        public string wechatClassStartNotSignIn(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.pushWechatClassStartNotSignIn,"");
            return callback;
        }
        #endregion

        #region 微信进行推送作业
        public string wechatPushWork(string openId,WechatModelDataList list) {
            string callback = wechatSendMsg(openId, list, Constance.pushWorkInfo, " https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0efd04edbbba705e&redirect_uri=https://www.chire.net/chireh5/Work/work_list.html&response_type=code&scope=snsapi_userinfo&state=smart#wechat_redirect");
            return callback;
        }
        #endregion

        #region 微信进行课程通知
        public string wechatPushClassEvent(string openId ,WechatModelDataList list){
            string callback = wechatSendMsg(openId, list, Constance.classEvent, "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0efd04edbbba705e&redirect_uri=https://www.chire.net/chireh5/Memorandum/Memorandum.html&response_type=code&scope=snsapi_userinfo&state=smart#wechat_redirect");
            return callback;
    }
        #endregion

        #region 微信 - 家长绑定小孩，家长获得通知
        public string wechatBindingStudentInfo(string openId, WechatModelDataList list)
        {
            string callback = wechatSendMsg(openId, list, Constance.bindingSuccess, "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0efd04edbbba705e&redirect_uri=https://www.chire.net/chireh5/identity/user_identity_choose.html&response_type=code&scope=snsapi_userinfo&state=smart#wechat_redirect");
            return callback;
        }
        #endregion


        #region Main微信进行发送消息
        public string wechatSendMsg(string openId, WechatModelDataList list, string pushTemp,string url)
        {
            string accessToken = getAccessToken();
            string nUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

            string template_id = pushTemp;
            string appid = Constance.wechatAppID;

            WechatModel model = new WechatModel();
            model.appid = appid;
            model.data = list;
            model.template_id = template_id;
            model.touser = openId;
            if (url.Length > 0) {
                model.url = url;
            }
            

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), model);
            string data = sw.GetStringBuilder().ToString();

            string callback = HttpPost(nUrl, data);
            return callback;
        }
        #endregion

        #endregion

        #region 进行插入menu
        public string wechatMenuAdd() { 
            string token = getAccessToken();

            Wechat_Menu_Action menuAction = new Wechat_Menu_Action();
            List<Menu_Model> menuModelList = menuAction.wechatMenuAddActionManager("");
            Menu_Button_Model MenuRootModel = new Menu_Button_Model();
            MenuRootModel.button = menuModelList;


             JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), MenuRootModel);
            string info = sw.GetStringBuilder().ToString();
    
            string newStr = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+getAccessToken();
            string back = HttpPost(newStr, info);

            return back;
        }
        #endregion

        #region 获取素材
        public string sucaiManager()
        {

            string nUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + getAccessToken();

            string type = "image";
            string offset = "0";
            string count = "20";

            sucaiModel sucaiModel = new sucaiModel();
            sucaiModel.type = type;
            sucaiModel.offset = offset;
            sucaiModel.count = count;

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), sucaiModel);
            string data = sw.GetStringBuilder().ToString();
           return HttpPost(nUrl, data);
        }


        #endregion

        #region 设置所属行业
        public string settingHangye() { 
            string accessToken = getAccessToken();
            string nUrl = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token="+accessToken;
            string data = "industry_id1=16&industry_id2=1";
            string back = HttpPost(nUrl, data);
            return back;
        }
        #endregion

        #region 获取所属行业
        public string getHangye() {
            string accessToken = getAccessToken();
            string nUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=" + accessToken;
            string back = HttpGet(nUrl, "");
            return back;
        }
        #endregion

        #region 1.Get请求

        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        } 

        #endregion

        #region 2.Post请求
        /// <summary> 
        /// POST请求与获取结果 
        /// </summary> 
        public static string HttpPost(string url, string postDataStr)
        {
            string strReturn;
            //在转换字节时指定编码格式
            byte[] byteData = Encoding.UTF8.GetBytes(postDataStr);

            //配置Http协议头
            HttpWebRequest resquest = (HttpWebRequest)WebRequest.Create(url);
            resquest.Method = "POST";
            resquest.ContentType = "application/x-www-form-urlencoded";
            resquest.ContentLength = byteData.Length;

            //发送数据
            using (Stream resquestStream = resquest.GetRequestStream())
            {
                resquestStream.Write(byteData, 0, byteData.Length);
            }

            //接受并解析信息
            using (WebResponse response = resquest.GetResponse())
            {
                //解决乱码：utf-8 + streamreader.readToEnd
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                strReturn = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
            }

            return strReturn;
        }
        #endregion


        #region ============ 微信小程序 ===============

        public Wechat_SmallProject_Model getcode2SessionManager(string jsCode)
        {
            Wechat_SmallProject_Model smallProjectModel = new Wechat_SmallProject_Model();

            string url = "https://api.weixin.qq.com/sns/jscode2session?appid="+Constance.smallProjectAppId+"&secret="+Constance.smallProjectSecret+"&js_code="+jsCode+"&grant_type=authorization_code";
            string info = HttpGet(url, "");

            JObject jo = (JObject)JsonConvert.DeserializeObject(info);
            if (jo.Property("errcode") == null || jo.Property("errcode").ToString() == "")
            {
                string session_key = jo["session_key"].ToString();
                string openid = jo["openid"].ToString();
                smallProjectModel.session_key = session_key;
                smallProjectModel.openid = openid;
            }
            else {
                string errcode = jo["errcode"].ToString();
            }

            return smallProjectModel;
        }
        #endregion

    }






   
}